var organizationAndManagement={
    init:function(){
        var self=this;
        self.shadeDiv = $("#shade-div");
        self.bindEvents();
        //self.loadTree()
    },
    bindEvents:function(){
        var self=this;
//        全选
        $.checkAll("inputItem1");
        $.checkAll("inputItem2");
        $.checkAll("inputItem3")
        $("#findGroup").textClean();
        $("#searchDep").textClean();
        //        搜索
        $("#searchName input").textClean()
        $("#searchName input").focus(function(){
            $(this).siblings("span").show();
        })
        $("#searchName input").blur(function(){
            if($.trim($(this).val()) == ""){
                $(this).siblings("span").hide();
            };

        })
        $(".removeSearch").click(function(){
            $(this).siblings("input").val("")
        })
        $('.searchName').keydown(function(e){
                if(e.keyCode==13){
                    $(this).click(); //处理事件
                }
        });

        //        show新增用户div
        $("#newUsers").click(function(){
            self.shadeDiv.show();
            $('#addUsers').setPosition().show();

        });
        
      //保存用户
        $("#btnSave").click(function(){
        	var deptid=$("#deptid").val();
        	//alert(deptid);
        $.post("../userconfig/user_config!save.xhtml", $("#addUserForm").serialize(),function(data){
        	
        	
        	 if(data=='true'){
        		// alert("添加成功");
        		 artDialog({icon: 'succeed',title: '提示',lock: true,opacity: 0.2,zIndex:8888,content:"添加成功",button:[{name: '确定'}]});
        		 var myDate = new Date();
        		 
        		 var deptids=$("#deptids").val(); 
        	// $('#iframepage',window.parent.document).attr('src',"../userconfig/user_config!list.xhtml?deptid="+deptid+"&deptids="+deptids);
        	 
        	  $.ajax({
				  url: "../userconfig/user_config!deptidsPut.xhtml",
				  type: "POST",
				  data:{deptids:deptids,deptid:deptid},
				  success: function(date){
					  $("#iframepage",window.parent.document).attr("src","../userconfig/user_config!list.xhtml?deptid="+deptid);    
			    }
				});
        	 
        	 
        	 //$('#iframepage',window.parent.document).attr('src', $('#iframe').attr('src'));
        	 }else{
        		 //alert(data);
        		 artDialog({icon: 'warning',title: '提示',lock: true,opacity: 0.2,zIndex:8888,content:data,button:[{name: '确定'}]});
        	 }
        	// $('#iframepage').attr('src', $('#iframe').attr('src'));
        	 //$("#iframepage").attr("src","../userconfig/user_config!list.xhtml?deptid="+treeNode.id);
        });
        	// $('#addUsers').setPosition().hide();
        });
        
        
        //修改用户
        $("#updateBtn").click(function(){
        	var uid=$("#Qid").val();
        	var name= $("#Quname").val();
        	var userCode= $("#QuserCode").val();
        	var phone= $("#Qphone").val();
        	var birth= $("#Qbirth").val();
        	var Quserype= $("#Quserype").val();
        	var  Qsex=  $('input[name="Qsex"]:checked').val();
        	
        	var Qemail= $("#Qemail").val();
        	var Qfax= $("#Qfax").val();
        	var Qlocal= $("#Qlocal").val();
        	var Qhometel= $("#Qhometel").val();
        	var Qemergencyphone= $("#Qemergencyphone").val();
        	var Qaddress= $("#Qaddress").val();
     	
          	$.ajax({
        		type : "POST",
        		url : "../userconfig/user_config!update.xhtml",
        		data : {id:uid,name:name,userCode:userCode,phone:phone,birth:birth,user_type:Quserype,sex:Qsex,email:Qemail,fax:Qfax,local:Qlocal,hometel:Qhometel,emergencyphone:Qemergencyphone,address:Qaddress},
        		beforeSend : function() {
        		},
        		success : function(data) {
        			//alert(data);
        			artDialog({icon: 'succeed',title: '提示',lock: true,opacity: 0.2,zIndex:8888,content:data,button:[{name: '确定'}]});
        			$("#x"+uid).html(name);
        			if(Qsex==1){
        				$("#z"+uid).html("男");
        			}else if(Qsex==0){
        				$("#z"+uid).html("女");
        			}
        		}
        	});
     
        });
        
        
//        常联系人
       /* $(".contacts").click(function(){
            self.shadeDiv.show();
            $('#contacts').setPosition().show();

        });*/
        
        var uid=null;
        $(".contacts").click(function(){
        	
        	uid= $(this).find("span").attr("id");
        	var utxt= $(this).find("span").html();
        	
            self.shadeDiv.show();
            if(utxt.indexOf("非") >= 0){
            	
            $('#warning2').setPosition().show().find("p.center").html("确定要设置为常用联系人吗？");
            }else{
            	 $('#warning2').setPosition().show().find("p.center").html("确定要取消常用联系人吗？");
            }

        });
        
       $("#btnLxr").click(function(){
    	   $('#warning2').setPosition().hide();
         	$.ajax({
        		type : "POST",
        		url : "../userconfig/user_config!updateLxr.xhtml",
        		data : {id:uid},
        		beforeSend : function() {
        		},
        		success : function(data) {
        		//alert(data);
        		 artDialog({icon: 'succeed',title: '提示',lock: true,opacity: 0.2,zIndex:8888,content:data,button:[{name: '确定'}]});
        		var obj= $("#"+uid).html();
        		if(obj=='常用联系人'){
        			$("#"+uid).html("非常用联系人");
        		}else{
        			$("#"+uid).html("常用联系人");
        		}
        		}
        	});
        	

        });
        

     /*   //        禁用
        $(".disable").click(function(){
        	
            self.shadeDiv.show();
            $('#warning').setPosition().show().find("p.center").html("确定要禁用该用户吗？");
        });

//        启用
        $(".enable").click(function(){
            self.shadeDiv.show();
            $('#warning').setPosition().show().find("p.center").html("确定要启用该用户吗？");
        });*/

        $(".basicInformation").click(function(){
        	$("#Quname").val("");
 		    $("#QuserCode").val("");
 		    $("#Qphone").val("");
 		    $("#Qbirth").val("");
 		    
 		   $("#Qemail").val("");
 		   $("#Qfax").val("");
 		   $("#Qlocal").val("");
 		   $("#Qhometel").val("");
 		   $("#Qemergencyphone").val("");
 		   $("#Qaddress").val("");
 		    
        	//var  aa= $(this).find("span").attr('id');
        	var  uid= $(this).find("span").html();
        	$("#Qid").val(uid);
        	$.ajax({
        		type : "POST",
        		url : "../userconfig/user_config!userInfo.xhtml",
        		data : "id="+uid,
        		beforeSend : function() {
        		},
        		success : function(data) {
        			//alert("(" + data+ ")");
        			var obj = eval("("+data+")");
        		    var userype=obj.userype;
        		    var name=obj.name;
        		    var userCode=obj.userCode;
        		    var sex=obj.sex;
        		    var phone=obj.phone;
        		    var birth=obj.birth;
        		    
        		    var email=obj.email;
        		    var fax=obj.fax;
        		    var local=obj.local;
        		    var hometel=obj.hometel;
        		    var emergencyphone=obj.emergencyphone;
        		    var address=obj.address;
        		    $("#Qemail").val(email);
        		    $("#Qfax").val(fax);
        		    $("#Qlocal").val(local);
        		    $("#Qhometel").val(hometel);
        		    $("#Qemergencyphone").val(emergencyphone);
        		    $("#Qaddress").val(address);
        		    
        		    $("#Quname").val(name);
        		    $("#QuserCode").val(userCode);
        		    $("#Qphone").val(phone);
        		    if(birth!=null){
        		    	birth=birth.split(" ",1);
        		       $("#Qbirth").val(birth);
        		    }
        		    if(sex==0){
        		    	$("input:radio[name=Qsex]").eq(1).attr("checked",'checked');
        		    }else if(sex==1){
        		    	$("input:radio[name=Qsex]").eq(0).attr("checked",'checked');
        		    }
        		    if(userype==0){
        		    	$("#Quserype").find("option:selected").text("普通用户");
        		    }else if(userype==1){
        		    	$("#Quserype").find("option:selected").text("虚拟用户");
        		    }
        		    
        		}
        	});
            self.shadeDiv.show();
            $('#basicInformation').setPosition().show();
        });
        $(".tab_list li a").click(function(){
            $(this).parent("li").addClass("cur").siblings("li").removeClass("cur");
            var index=$(this).parent("li").index();
            $(this).parents("ul.tab_list").siblings(".tab_info").eq(index).show().siblings("div.tab_info").hide()
        });
//      新增部门
        $(".newDepartment").click(function(){
        	var treeObj = $.fn.zTree.getZTreeObj("areaTree");
    		var nodes = treeObj.getNodesByParam("id", $("#deptid").val(), null);
        	$("#maindeptname").html(nodes[0].name);
        	$("#SaveDeptsortmanager").val("" );
        	$("#SaveDeptname").val("");
            self.shadeDiv.show();
            $('#newDepartment').setPosition().show();
        });
        $("#saveButton").click(function(){
        	organizationAndManagement.ajaxPOST(ctx+"/userconfig/dept!save.xhtml","dept.pid="+$("#deptid").val()+"&dept.sortmanager="+$("#SaveDeptsortmanager").val()+"&dept.deptname="+$("#SaveDeptname").val(),function(data){
        		var treeObj = $.fn.zTree.getZTreeObj("areaTree");
        		var nodes = treeObj.getNodesByParam("id", $("#deptid").val(), null);
        		var newNode = {name:data.deptname,id:data.id};
        		newNode = treeObj.addNodes(nodes[0], newNode);
    			$("#newDepartment").hide();
                $("#shade-div").hide();	
        	});
        });
        
        //        编辑部门
        $(".edit").click(function(){
        	organizationAndManagement.ajaxPOST(ctx+"/userconfig/dept!getDeptInfo.xhtml","dept.id="+$("#deptid").val(),function(data){
        		$("#EditDeptid").val(data.id);
        		$("#EditDeptname").val(data.deptname);
        	});
            self.shadeDiv.show();
            $('#orgEdi').setPosition().show();

        });
        
        $("#updateButton").click(function(){
        	organizationAndManagement.ajaxPOST(ctx+"/userconfig/dept!update.xhtml","dept.id="+$("#EditDeptid").val()+"&dept.deptname="+$("#EditDeptname").val(),function(data){
        		var treeObj = $.fn.zTree.getZTreeObj("areaTree");
        		var nodes = treeObj.getNodesByParam("id", $("#EditDeptid").val(), null);
        		nodes[0].name = $("#EditDeptname").val();
    			treeObj.updateNode(nodes[0]);
    			 $("#orgEdi").hide();
               $("#shade-div").hide();
        	});
        });	
//      删除部门
        $(".del").click(function(){
        	//是否有下一级
        	var treeObj = $.fn.zTree.getZTreeObj("areaTree");
    		var nodes = treeObj.getNodesByParam("pId", $("#deptid").val(), null);
    		if(nodes.length>0){
    			$('#warning1').setPosition().show().find("p.center").html("存在子部门，不能进行删除操作.");
    			self.shadeDiv.show();
    			return ;
    		}else{
    			//服务器验证部门下的人数
    			var node = treeObj.getNodesByParam("id", $("#deptid").val(), null);
    			if(node[0].id=="99999"){
    				$('#warning1').setPosition().show().find("p.center").html("此菜单不能进行删除操作");
        			self.shadeDiv.show();
        			return ;
    			}else{
    				organizationAndManagement.ajaxPOST(ctx+"/userconfig/dept!getTotalByDeptId.xhtml","dept.id="+$("#deptid").val(),function(data){
    					$('#warning').setPosition().show().find("p.center").html("确定要删除“"+node[0].name+"”吗？该部门下有"+data.total+"个人员，部门删除后人员将被放入调离区！");
            			self.shadeDiv.show();
    	        	});
    			}
    		}
        });
        $("#deleteButton").click(function(){
        	organizationAndManagement.ajaxPOST(ctx+"/userconfig/dept!delete.xhtml","dept.id="+$("#deptid").val(),function(data){
        		window.location.reload();
        	});
        });
        
        //       设置子部门排序
        $("#sortable").sortable({
            axis:"y"
        });
        $(".sort").click(function(){
        	$("#sortable").html("");
        	organizationAndManagement.ajaxPOST(ctx+"/userconfig/dept!getDeptByPid.xhtml","dept.pid="+$("#deptid").val(),function(data){
        		var ht="";
        		for(var i=0;i<data.length;i++){
        			ht+="<li id=\""+data[i].id+"\" class=\"ui-state-default\">"+data[i].name+"</li>";
        		}
        		$("#sortable").html(ht);
        	});
            self.shadeDiv.show();
            $('#sort').setPosition().show();
        });
        $("#sortButton").click(function(){
        	var sortedIDs = $("#sortable").sortable("toArray");
        	organizationAndManagement.ajaxPOST(ctx+"/userconfig/dept!updateSort.xhtml","deptids="+sortedIDs,function(data){
        		window.location.reload();
        	});
        });
        
    },
    loadTree:function(){
        $.fn.zTree.init($("#treeDemo"), setting, zNode1);
        $.fn.zTree.init($("#treeDemo1"), setting1, zNode1);
//        $.fn.zTree.init($("#treeDemo2"), setting1, zNode1);
//        $.fn.zTree.init($("#treeDemo3"), setting, zNode1);
        /*$.fn.zTree.init($("#treeDemo4"), setting2, zNode1);
        $.fn.zTree.init($("#treeDemo5"), setting2);*/
    },
    ajaxGET:function (url, data, fn,beforeSendFn) {
        var beforeSendFn = beforeSendFn || function(){};
        $.ajax({type:"GET", dataType:'json', context:this, url:url, data:data, success:fn, beforeSend:beforeSendFn});
    },
    ajaxPOST:function (url, data, fn,beforeSendFn) {
        var beforeSendFn = beforeSendFn || function(){};
        $.ajax({type:"POST", dataType:'json', context:this, url:url, data:data, success:fn, beforeSend:beforeSendFn});
    }
}
$(function(){
    organizationAndManagement.init()
})

var zid="";
var ztype="";
function qy(id,type){
	zid=id;
	ztype=type;
	if(type==1){
	 $('#warning3').setPosition().show().find("p.center").html("确定要启用当前用户？");
	}else if(type==0){
	  $('#warning3').setPosition().show().find("p.center").html("确定要禁用当前用户？");
	}

	
}

function qyok(){
	
	 $('#warning3').setPosition().hide();
	$.ajax({
		type : "POST",
		url : "../userconfig/user_config!updateState.xhtml",
		data : "id="+zid+"&utype="+ztype,
		beforeSend : function() {
		},
		success : function(data) {
			
		    // $('#warning').setPosition().show().find("p.center").html(data);
			if(ztype==1){
				//alert("启用成功");
				artDialog({icon: 'succeed',title: '提示',lock: true,opacity: 0.2,zIndex:8888,content:"启用成功",button:[{name: '确定'}]});
				$("#ss"+zid).html("已启用");
				$("#ss"+zid).attr("href","javascript:qy("+zid+",0)");
				
			}else if(ztype==0){
				//alert("禁用成功");
				artDialog({icon: 'succeed',title: '提示',lock: true,opacity: 0.2,zIndex:8888,content:"禁用成功",button:[{name: '确定'}]});
				$("#ss"+zid).html("已禁用");
				$("#ss"+zid).attr("href","javascript:qy("+zid+",1)");
			}
		}
	});
	
	
}
